package com.qidianit.mes.masterdata.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidianit.mes.common.pojo.MesResult;
import com.qidianit.mes.masterdata.service.MaterialService;
import com.qidianit.mes.pojo.Material;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @company 起点编程
 * @author 戴着假发的程序员
 * @date 2025/7/22
 * @description 物料Controller
 */
@RestController
@RequestMapping("/materials")
public class MaterialController {

    @Autowired
    private MaterialService materialService;
    @Value("${server.port}")
    private String port;

    @RequestMapping(params = {"userId","username"},value = "/xx",method = RequestMethod.GET)
    public String test(){
        return "";
    }
    @RequestMapping(value = "/xx",method = RequestMethod.POST)
    public String test1(){
        return "123123";
    }

    @GetMapping("/page")
    public MesResult<IPage<Material>> page(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int pageSize,Material material){
        IPage pager = new Page(page, pageSize);
        QueryWrapper<Material> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(material.getMaterialName() != null, "material_name", material.getMaterialName());
        queryWrapper.like(material.getSpecification() != null, "specification", material.getSpecification());//
        return MesResult.success(materialService.page(pager,queryWrapper));
    }

    /**
     * 查询所有物料
     */
    @GetMapping
    public MesResult<List<Material>> getAllMaterials() {
        return new MesResult<>(200,port,materialService.list());
    }

    /**
     * 根据ID查询物料
     */
    @GetMapping("/{id}")
    public MesResult<Material> getMaterialById(@PathVariable String id, HttpServletRequest request) {
        System.out.println("在getMaterialById中获取登录用户信息:" );
        System.out.println(request.getAttribute("loginUser"));
        return new MesResult<>(200,port,materialService.get(id));
    }

    /**
     * 新增物料
     */
    @PostMapping
    public MesResult<Boolean> createMaterial(@RequestBody Material material) {
        return MesResult.success(materialService.save(material));
    }

    /**
     * 更新物料
     */
    @PutMapping("/{id}")
    public MesResult<Boolean> updateMaterial(@PathVariable String id, @RequestBody Material material) {
        material.setMaterialId(id);
        return MesResult.success(materialService.updateById(material));
    }

    /**
     * 删除物料
     */
    @DeleteMapping("/{id}")
    public MesResult<Boolean> deleteMaterial(@PathVariable String id) {
        return MesResult.success(materialService.removeById(id));
    }
}